import { Comment, Modal, message, Avatar } from 'antd';
import React, { useEffect, useState } from 'react';
import $ from 'jquery';
import intl from 'react-intl-universal';
import { storage } from '../../utils/localstorage';


const ApplyToComment = (props) => {
  return (
    <div>
      <textarea placeholder='想说些什么' value={props.comment} maxLength={128} style={{width:'100%', borderRadius:'4px', padding:'0 16px'}}
        onChange={props.handleChange} />
      <div style={{color:'#fff', backgroundColor:'red', width:'60px', height:'24px', borderRadius:'16px', textAlign:'center'}}
        onClick={props.handleSubmit} className='submitCommentBtn' >
        评论
      </div>
    </div>
  );
};


const MyComment = (props) => {
  const [commentData, setCommentData] = useState([]);               // 从后端获取的原始评论数据
  const [hasChange, setHasChange] = useState(true);                 // 是否需要从后端获取数据
  const [handleCommentData, setHandleCommentData] = useState(false);// 是否需要对原始评论数据进行处理
  const [dataSource, setDataSource] = useState([]);                 // 由处理后的评论数据生成的Comment组件

  const [modalVisiable, setModalVisiable] = useState(false);
  const [param, setParam] = useState({
    name: '',
    parent: 0,
  });
  const showModal = (username, parent) => {
    console.log('huifu', username, parent)
    setParam({
      name: username,
      parent: parent,
    });
    setModalVisiable(true);
  }
  const handleCancle = () => {
    setModalVisiable(false);
  }


  // 获取评论数据
  useEffect(() => {
    const getComments = () => {
      $.ajax({
        url: '/home/comment',
        data: {aid: props.data.id},
        type: 'post',
        dataType: 'json',
        success: function(result) {
          if (result.status === 1) {
            // console.log(result.data)
            setCommentData(result.data);
            setHandleCommentData(true);
          } else {
            message.info('数据获取失败，请稍后再试');
          }
        },
        error: function(err) {
          alert(JSON.stringify(err));
        },
      });
    };
    hasChange && getComments();
    setHasChange(false);
  }, [hasChange]);


  // 评论内容
  const [comment, setComment] = useState('');
  const handleChange = (event) => {
    setComment(event.target.value);
  };


  // 发布评论
  const handleSubmit = (name, parent) => {
    if (!comment)
      return;
    $.ajax({
      url: '/home/comment/add',
      data: {
        aid: props.data.id,
        comment: storage.get('user').username + '|' + comment + '|' + name,
        parent: parent,
        uid: storage.get('user').uid,
        type: 5,
      },
      type: 'post',
      dataType: 'json',
      success: function(result) {
        handleCancle();
        setHasChange(true);
        props.setHasChange(true);
        if (result.status === 1) {
          setComment('');
          message.success('评论成功');
        } else {
          message.info('评论失败，请稍后再试');
        }
      },
      error: function(err) {
        alert(JSON.stringify(err));
      },
    });
  };


  // 删除评论
  const handleDelete = (id, author) => {
    let data = {};
    if (storage.get('user').username === author)
      data = {cid:id, uid:storage.get('user').uid, type:6};
    else
      data = {cid:id};
    $.ajax({
      url: '/home/comment/delete',
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(result) {
        if (result.status === 1) {
          setHasChange(true);
          props.setHasChange(true);
          message.success('删除成功');
        }
        else
          message.info('删除失败，请稍后再试');
      },
      error: function(err) {
        alert(JSON.stringify(err));
      }
    })
  };


  // 将原始评论数据，处理成两级嵌套评论
  const createCommentData = (data) => {
    let temp = [];
    let roots = data.filter(item => item.parent === 0);
    temp.push(...roots);
    const getChildren = (tempData, data) => {
      tempData.forEach((item) => {
        item.children = data.filter(element => element.parent === item.cid);
      });
    };
    getChildren(temp, data);
    return temp;
  };


  // 利用两级嵌套评论数据，生成Comment组件
  const createCommentDataII = (data) => {
    if (storage.get('user') === null || storage.get('user') === undefined || storage.get('user') === {}) {
      alert(intl.get('messageOfLogin'));
      window.location.replace('/login');
      return;
    }
    let temp = [];
    if (data !== undefined) {
      data.map((item) => {
        temp.push(
          <Comment 
            key={item.cid}
            actions={
              (storage.get('user').roles.roleName.indexOf('root') !== -1 || item.comment.split('|')[0] === storage.get('user').username) ?
              [<div className='deleteComment' style={{fontSize:'12px'}} onClick={() => handleDelete(item.cid, item.comment.split('|')[0])}>删除</div>,
               <div className='applyComment' style={{fontSize:'12px'}} onClick={() => showModal(item.comment.split('|')[0], item.parent === 0 ? item.cid : item.parent)}>回复</div>,] :
              [<div className='applyComment' style={{fontSize:'12px'}} onClick={() => showModal(item.comment.split('|')[0], item.parent === 0 ? item.cid : item.parent)}>回复</div>,]
            }
            author={
              (item.comment.split('|')[2] !== '') ?
              <div>
                <span style={{fontSize:'12px'}}>{item.comment.split('|')[0]}</span>
                <span style={{fontSize:'12px'}}>  回复 </span>
                <span style={{fontSize:'12px'}}>{item.comment.split('|')[2]}</span>
              </div> :
              <div>
                <span style={{fontSize:'12px'}}>{item.comment.split('|')[0]}</span>
              </div>
            }
            avatar={<Avatar src='https://joeschmoe.io/api/v1/random' />}
            content={<p>{item.comment.split('|')[1]}</p>}
          >
            {createCommentDataII(item.children)}
          </Comment>
        );
        return null;
      });
    }
    return temp;
  };


  // 触发数据处理方法
  useEffect(() => {
    let result = [];
    if (handleCommentData) {
      result = createCommentData(commentData);  // 将原始评论数据，处理成两级嵌套评论
      result = createCommentDataII(result);     // 利用两级嵌套评论数据，生成Comment组件
      setDataSource(result);
    }
  }, [handleCommentData, commentData]);


  return (
    <div>
      <Modal footer={null} visible={modalVisiable} destroyOnClose='true' title={'回复'} onCancel={handleCancle} onOk={handleCancle}>
        <ApplyToComment comment={comment} handleChange={handleChange} handleSubmit={() => handleSubmit(param.name, param.parent)} />
      </Modal>
      <Comment 
        avatar={<Avatar src='https://joeschmoe.io/api/v1/random' />}
        content={<ApplyToComment comment={comment} handleChange={handleChange} handleSubmit={() => handleSubmit('', 0)} />}
      />
      {console.log('dataSource', dataSource)}
      {dataSource}
    </div>
  );
};

export default MyComment;